package Service

import (
	"github.com/astaxie/beego/logs"
	"net"
	"time"
)

type myWriter struct {
	destAddr  string
	bufChan   chan []byte
	destConn  net.Conn
	isRunning bool
}

func (m *myWriter) start() {
	m.isRunning = true
	go func() {
		for m.isRunning {
			var err error = nil
			m.destConn = nil
			m.destConn, err = net.DialTimeout("tcp", m.destAddr, 10*time.Second)
			if err != nil {
				logs.Debug("连接次目标超时：%s, %s", m.destAddr, err.Error())
				time.Sleep(time.Millisecond * 1000 * 10)
				continue
			}
			logs.Debug("连接次目标成功: ", m.destConn.LocalAddr(), " -> ", m.destConn.RemoteAddr())
			// 使用for循环遍历通道中的元素并打印
			for v := range m.bufChan {
				if !m.isRunning {
					break
				}
				_, err = m.destConn.Write(v)
				if err != nil {
					logs.Error("次目标转发数据: ", err.Error())
					break
				}
				logs.Debug("次目标转发数据: ", string(v))
				time.Sleep(time.Second * 0)
			}
			CloseConn(m.destConn)
			logs.Debug("转发次目标出错：", m.destAddr)
		}
	}()
}
func (m *myWriter) stop() {
	m.isRunning = false
	CloseConn(m.destConn)
	CloseChan(m.bufChan)
}
